﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace MvvmEx.Behaviors
{
    public class CanDragBehavior : Behavior<FrameworkElement>
    {
        private Window _view;

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;

            _view = GetWindow(this.AssociatedObject) as Window;
        }

        private void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.ButtonState == MouseButtonState.Pressed)
            {
                _view?.DragMove();
            }
        }

        /// <summary>
        /// 向上遍历找到Window
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DependencyObject GetWindow(DependencyObject obj)
        {
            var parent = LogicalTreeHelper.GetParent(obj);

            if (parent is Window)
            {
                return parent;
            }
            else
            {
                return GetWindow(parent);
            }
        }
    }
}